//
//  YZEmoticonViewController.swift
//  Emoticon_Keyboard
//
//  Created by 杨振 on 15/10/17.
//  Copyright © 2015年 杨振. All rights reserved.
//

import UIKit
/// 可重用Cell的标识符
private let YZEmoticonCellIdentifier = "YZEmoticonCellIdentifier"
class YZEmoticonViewController: UIViewController {

    // 定义表情闭包
    var selectedEmoticonCallBack: (emoticon: Emoticon) -> ()
    init (selectedEmoticon: (emoticon: Emoticon) -> ()) {

        selectedEmoticonCallBack = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 监听方法
    /// 选中工具栏按钮
    func clickItem(item: UIBarButtonItem) {

        // 滚动到指定组
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    // 添加子控件
    private func setupUI() {
        view.addSubview(toolbar)
        view.addSubview(collectionView)
        
        // 自动布局控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["cv": collectionView, "tb": toolbar]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(40)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        // 准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    /// 准备CillectionView
    private func prepareCollectionView() {
    
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: YZEmoticonCellIdentifier)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.whiteColor()
    }
    /// 准备Toolbar
    private func prepareToolbar() {
    
        toolbar.backgroundColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        for p in packages {
            // 添加 Item
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            // 添加 弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    // MARK: - 懒加载控件
    /// 懒加载并实例化出一个表情数组 等待调用
    private lazy var packages = EmoticonPackage.packages()
    
    private lazy var toolbar = UIToolbar()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: YZEmoticonLayout())
    
    // MARK: - 表情键盘布局 - 私有类
    private class YZEmoticonLayout: UICollectionViewFlowLayout{

        private override func prepareLayout() {
            // 设置布局属性
            let w = collectionView!.bounds.width / 7.0
            // 提示：由于浮点数计算的问题，如果是 0.5，在 iPhone 4s 的模拟器，只能显示 2 行
            // 工作中，实际测试一定要测试所有的屏幕！
            let y = (collectionView!.bounds.height - 3 * w) * 0.499
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}
// MARK: - Cell 的数据源方法
extension YZEmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        // 完成回调
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        selectedEmoticonCallBack(emoticon: emoticon)
        
    }
    
    /// 返回分组的数量 - 返回表情包的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    /// 返回每一个表情包 - 表情的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 1.根据section取出每一组模型  
        // 2.根据emoticons取出模型数组 
        // 3.再根据count取出模型数组中的个数 ?? 0
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YZEmoticonCellIdentifier, forIndexPath: indexPath) as! EmoticonCell
        
        // 1.给cell中的emoticon数据模型赋值
        // 2.根据section 找到对应的组
        // 3.根据对应的emoticons找到对应的组的模型信息
        // 4.根据indexPath.item 取出组中的每一组数据模型信息 (chs: png: id: )
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
}
/// 表情 Cell
private class EmoticonCell: UICollectionViewCell {
    
    // 实例一个表情数据模型 给cell赋值
    var emoticon: Emoticon? {
        didSet {
            // 设置按钮的图像   -> 使用技巧  上面一句话就可以解决图片的复用问题
            // contentsOfFile 如果路径不存在(图像不存在)，会返回 nil，setImage -> 清空按钮的图片
            // 设置按钮的图像              根据文件路径中的内容获取图片信息 给按钮赋值
            // 是一种 [可爱] 属性为本的表情符号
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            // 设置emoji < 是一种字符型表情符号，可以通过字体大小改变表情大小 >
            emoticonButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            
            // 判断是否是删除按钮
            if emoticon!.removeEmoticon {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
        }
    }
    
    // 提示：frame 已经有准确的数值，frame的数值来源是
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        emoticonButton.backgroundColor = UIColor.whiteColor()
        // 设定相对 bounds 的缩进后的 rect
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel!.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
        
        addSubview(emoticonButton)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 懒加载控件
    private lazy var emoticonButton = UIButton()
}

